<template>
  <div>
    <a-modal
      :visible="visible"
      :maskClosable='false'
      width='40%'
      :title="$t('Create-OSD')"
      @cancel="cancelhandle"
      :bodyStyle="{height:'370px'}"
      v-dragModal
	  >
      <a-steps :current="current">
        <a-step v-for="item in steps" :key="item.title" 
                :title="$store.state.language=='zh'? item.ch_title : item.en_title" 
                :description="$store.state.language=='zh'? item.ch_desc : item.en_desc" />
      </a-steps>
      <div class="steps-content">
        <a-form :form='form'>
          <!--步骤一-->
          <div v-if="current==0">
            <div class="tips">
              <img src="../../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img"/>
              <span v-if="$store.state.language=='zh'">一个OSD磁盘对应一块物理磁盘，您的机架中尚有<span>{{inactivePhyDisks.length}}块</span>物理磁盘尚未激活，可从中选择一块用于创建OSD磁盘。HDD磁盘只能用作数据盘，SSD盘可作缓存盘，也可作数据盘。</span>
              <span v-else>One OSD disk corresponds to one physical disk. There are still<span> {{inactivePhyDisks.length}} </span>physical disks in your rack that have not been activated. You can choose one of them to create an OSD disk. HDD disk can only be used as a data disk, SSD disk can be used as a buffer disk, or as a data disk.</span>
            </div>
            <!--磁盘选择-->
            <a-form-item :label="$t('Choose-disk')+'：'" v-bind='formlayout' has-feedback>
              <a-select v-decorator="['phy_disk',{
                    rules:[{required:true,message:$t('Choose')+$t('Phy-disk')},],initialValue:phy_disk!=''?phy_disk:undefined}]"
                    @change="handleChangeDisk" :placeholder="$t('Choose')+$t('Phy-disk')">
                <a-select-option v-for="item in inactivePhyDisks" :value="item.disk+'?'+item.type+'@'+item.total +'#'+item.id" :key="item.id">
                  {{item.disk}}，{{ diskTypeMap.get(item.type) }}，{{$t('Total-space')+item.total}}
                </a-select-option>
                <!-- <a-select-option value="hdd">hdd</a-select-option> -->
              </a-select>
            </a-form-item>
            <!--SSD盘用途-->
            <a-form-item v-if="isShowSSDUsage" :label="$t('Disk-usage')+'：'" v-bind='formlayout' has-feedback>
              <a-select v-decorator="['ssd_usage',{
                    rules:[{required:true,message:$t('Disk-choose-tip')},],initialValue:ssd_usage!='' ?ssd_usage :undefined}]"
                    :placeholder="$t('Disk-choose-tip')">
                <a-select-option v-for="(disk,index) in diskTypeData" :key="index" :value="disk.value">{{$store.state.language==='zh'?disk.ch_name:disk.en_name}}</a-select-option>
                <!-- <a-select-option value="0">{{$t('Data-disk')}}</a-select-option>
                <a-select-option value="1">{{$t('Cache-disk')}}</a-select-option>  -->
              </a-select>
            </a-form-item>
          </div>

          <!--步骤二-->
          <div v-else-if="current==1">
            <div class="tips">
              <img src="../../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img"/>
              <span v-if="$store.state.language=='zh'">本系统支持对磁盘进行分区，还支持保留磁盘原有分区，如果您选择分区，系统将对磁盘进行<span class="weightAndRed">格式化</span>并根据您选择的分区数量等分磁盘可用空间，该操作将清除磁盘原有全部分区信息及数据，请注意保存。
                <div style="display:inline-block" v-if="diskType==1">您选择的是<span class="weightAndBlue">HDD</span>类型的盘，建议不要进行分区。</div>
              </span>
              <span v-else>The system supports partitioning the disk and retaining the original partition of the disk. If you choose partition, the system will <span class="weightAndRed">format</span> the disk and divide the available space of the disk according to the number of partitions you choose. This operation will clear all the original partition information and data of the disk. Please pay attention to saving.
                <div style="display:inline-block" v-if="diskType==1">You have selected a <span class="weightAndBlue">HDD</span> type disk. It is not recommended to partition.</div>
              </span>
            </div>
            <!--磁盘分区-->
            <!--有分区就显示-->
            <div v-if="hasPartition"><!--v-if="hasPartition isKeepOldPartition"-->
              <a-form-item label="" v-bind='formlayout'>
                <a-checkbox v-model="isKeepOldPartition" @change="onChangeCheckBox">
                  <span v-if="$store.state.language=='zh'">保留原有分区及可用空间比例</span>
                  <span v-else>Keep the original partition and free space ratio</span>
                </a-checkbox>
              </a-form-item>
              <div v-show="isKeepOldPartition">
                <div v-if="$store.state.language=='zh'">磁盘原有 <span class="weightAndBlue">{{partitionData.length}}</span> 个分区，可用分区分别为：</div>
                <div v-else>The disk has <span class="weightAndBlue">{{partitionData.length}}</span> original partitions, and the available partitions are:</div>
                <div>
                  <span v-for="(item,index) in partitionData" :key="index">
                    <span v-if="index!=partitionData.length-1">{{item}}、</span>
                    <span v-else>{{item}}</span>
                  </span>
                </div>
              </div>
            </div>
            <!--没有分区就显示-->
            <a-form-item v-if="!hasPartition || !isKeepOldPartition" label="磁盘分区：" v-bind='formlayout' has-feedback>
              <a-select v-decorator="['disk_partition',{
                    rules:[{required:true,message:$t('Choose')+$t('Partition')},],initialValue:disk_partition!=''?disk_partition:undefined}]"
                    :placeholder="$t('Choose')+$t('Partition')">
                <a-select-option value="0">{{$t('No-partition')}}</a-select-option><!--不分区-->
                <a-select-option value="2">{{$t('Divided-two-area')}}</a-select-option><!--分二区-->
                <a-select-option value="3">{{$t('Divided-three-area')}}</a-select-option><!--分三区-->
                <a-select-option value="4">{{$t('Divided-four-area')}}</a-select-option><!--分四区-->
              </a-select>
            </a-form-item>
            <div v-if="hasPartition && !isKeepOldPartition">
              <span v-if="$store.state.language=='zh'">原有分区将<span class="weightAndRed">清除</span>，系统将根据您选取的分区数量<span class="weightAndBlue">均分</span>整块磁盘。</span>
              <span v-else>The original partition will be <span class="weightAndRed">cleared</span>, and the system will <span class="weightAndBlue">divide the whole disk equally</span> according to the number of partitions you select.</span>
            </div>
          </div>

          <!--步骤三-->
          <div v-else-if="current==2">
            <!--保留了原有分区的提示-->
            <div class="tips" v-if="isKeepOldPartition">
              <img src="../../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img"/>
              <span v-if="$store.state.language=='zh'">您选择的磁盘类型为<span>{{diskType==0?'SSD':'HDD'}}</span>，物理空间为<span>{{diskCapacity}}</span>，您选择保留原有分区比例，创建OSD磁盘将会对磁盘进行<span class="weightAndRed">格式化</span>，您将丢失磁盘上的所有数据。此外，创建OSD磁盘后，整体可用空间将有一定比例的损失，请确认。</span>
              <span v-else>The disk type you choose is <span>{{diskType==0?'SSD':'HDD'}}</span>, and the physical space is <span>{{diskCapacity}}</span>. You choose to keep the original partition ratio. Creating an OSD disk will <span class="weightAndRed">format</span> the disk, and you will lose all data on the disk. In addition, after creating OSD disks, there will be a certain percentage of the loss of the overall available space. Please confirm.</span>
            </div>
            <div class="tips" v-else>
              <img src="../../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img"/>
              <span v-if="$store.state.language=='zh'">您选择的磁盘类型为<span>{{diskType==0?'SSD':'HDD'}}</span>，物理空间为<span>{{diskCapacity}}</span>，您选择将其分为<span>{{disk_partition==-1?0:disk_partition}}</span>个区，分区后每个区的可用空间均等，创建OSD磁盘将会对磁盘进行<span class="weightAndRed">格式化</span>，您将丢失磁盘上的所有数据。此外，创建OSD磁盘后，整体可用空间将有一定比例的损失，请确认。</span>
              <span v-else>The disk type you selected is <span>{{diskType==0?'SSD':'HDD'}}</span>, and the physical space is <span>{{diskCapacity}}</span>. You choose to divide it into <span>{{disk_partition==-1?0:disk_partition}}</span> zones. After partitioning, the free space of each zone is equal. Creating an OSD disk will <span class="weightAndRed">format</span> the disk, and you will lose all data on the disk. In addition, after creating OSD disks, there will be a certain percentage of the loss of the overall available space. Please confirm.</span>
            </div>
          </div>

          <!--步骤四-->
          <div v-else-if="current==3">
            <!--创建中-->
            <div v-if="createOSDStatus==0">
              <div class="configIngImg">
                <img src="../../../../../static/images/disk_check/64_f_ic_inservice.png" alt="config_img"/>
              </div>
              <div v-if="$store.state.language=='zh'" class="paragraph">
                正在创建OSD磁盘，此过程大约会耗时<span class="weightAndBlue">10~30秒</span>，请稍候。如不想继续等待请点击确定按钮，进程将切换到后台自动运行，创建成功后将会在OSD磁盘管理列表中新增记录，您可对其进行管理。
              </div>
              <div v-else class="paragraph">
                Creating OSD disk. This process will take about <span class="weightAndBlue">10~30</span> seconds. Please wait. If you don't want to wait, please click the OK button, and the process will switch to the background automatic operation. After the creation is successful, a new record will be added in the OSD disk management list, which you can manage.
              </div>
            </div>
            <!--创建成功-->
            <div v-else-if="createOSDStatus==1">
              <div class="configIngImg2">
                <img src="../../../../../static/images/disk_check/64_f_ic_sure.png" alt="sure_img"/>
              </div>
              <div v-if="$store.state.language=='zh'">
                <div class="paragraph">OSD磁盘创建成功，可用空间为<span class="weightAndBlue">{{diskCapacity}}</span>。</div>
                <!-- ，物理空间损失率为<span class="weightAndBlue">2%</span>，这是正常现象。 -->
                <div class="paragraph">您可在OSD磁盘管理列表中对磁盘进行管理。</div>
              </div>
              <div v-else>
                <div class="paragraph">OSD disk is successfully created, with <span class="weightAndBlue">{{diskCapacity}}</span> free space.</div>
                 <!-- and <span class="weightAndBlue">2%</span> physical space loss rate, which is a normal phenomenon. -->
                <div class="paragraph">You can manage disks in the OSD disk management list.</div>
              </div>
            </div>
            <!--创建失败-->
            <div v-else-if="createOSDStatus==2">
              <div class="configIngImg2">
                <img src="../../../../../static/images/disk_check//64_f_ic_error.png" alt="error_img"/>
              </div>
              <div v-if="$store.state.language=='zh'">
                <div class="paragraph">OSD磁盘创建失败，创建失败原因通常非常复杂，我们建议您直接联系售后人员进行排查。</div>
              </div>
              <div v-else>
                <div class="paragraph">OSD disk creation failed. The reasons for the creation failure are usually very complex. We suggest you directly contact after-sales personnel for troubleshooting.</div>
              </div>
            </div>
          </div>
        </a-form>
      </div>
      <template slot="footer">
        <div class="steps-action">
            <a-button v-show="current > 0 && current < steps.length - 1" @click="cancelhandle">{{$t('Cancel')}}</a-button>
            <a-button v-if="current > 0 && current < steps.length - 1" type="primary" style="margin-left: 8px" @click="prev">{{$t('Prev')}}</a-button>
            <a-button v-if="current < steps.length - 2" type="primary" @click="next">{{$t('Next')}}</a-button>
            <a-button v-if="current == 2" type="primary" @click="confirmCreateOSD">
              <span v-if="$store.state.language=='zh'">确认，创建OSD</span>
              <span v-else>Confirm, create OSD</span>
            </a-button>
            <a-button v-if="current == 3" type="primary" @click="cancelhandle">{{$t('Sure')}}</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import request from '@/request/request'

export default {
  name: "CreateOSD",
  props: ['visible', 'activeDisk'],
  data() {
    return {
      form:this.$form.createForm(this),
      current: 0,
      formlayout:{
        labelCol: {span:5},
        wrapperCol: {span:19}
      },
      steps: [
        {
          ch_title: '步骤一', ch_desc: '磁盘选择', en_title: 'Step 1', en_desc: 'Disk selection'
        },
        {
          ch_title: '步骤二', ch_desc: '磁盘分区', en_title: 'Step 2', en_desc: 'Disk partition'
        },
        {
          ch_title: '步骤三', ch_desc: '确认操作', en_title: 'Step 3', en_desc: 'Confirm'
        },
        { ch_title: '步骤四', ch_desc: '结果', en_title: 'Step 4', en_desc: 'Result'
        },
      ],
      isShowSSDUsage: false,
      phy_disk: '',
      phy_disk2: '',
      ssd_usage: '',
      disk_partition: '',
      hasPartition: true,//是否有分区
      isKeepOldPartition: true,
      createOSDStatus: 0,
      inactivePhyDisks: [],
      nowDiskStr: -1,
      partitionData: [],
      oldPartiteNum: -1,
      diskType: 0,
      diskCapacity: 0,
      diskId: -1,
      diskUsage: 0,
      diskTypeData: [
        {ch_name:'数据盘', en_name:'Data Disk', value: 0},
        {ch_name:'缓存盘', en_name:'Cache Disk', value: 1},
      ],
      diskTypeData_copy: [
        {ch_name:'数据盘', en_name:'Data Disk', value: 0},
        {ch_name:'缓存盘', en_name:'Cache Disk', value: 1},
      ],
      diskTypeMap: new Map([
        [0, 'SSD'],
        [1, 'HDD'],
        [2, 'NVMe']
      ]),
      diskName: '',
    }
  },
  mounted() {
    // this.$watch(
    //   function () {  // 第一个函数就是处理你要监听的属性，只要将其return出去就行
    //     return this.form.getFieldValue('phy_disk')
    //   },
    //   function (val, oldVal) {
    //     console.log('222222222222')
    //   }
    // )
  },
  watch: {
    visible(newValue) {
      if(newValue) {
        this.getInactivePhyDisk();
      }
    },
    phy_disk2(newValue) {//比较新选的盘是否与旧盘一样
      if(this.phy_disk !=newValue) {//不一样就重置第一步往后的内容
        this.resetFun();
      }
    },
  },
  methods: {
    //获取未激活的物理磁盘
    getInactivePhyDisk() {
      request('get', 'machine/disk/',{
        // params: {
          disk_application: 3
        // }
      }).then(res => {
        console.log('未激活的物理磁盘', res);
        this.inactivePhyDisks = res.data;
        if(this.activeDisk != -1) {
          this.inactivePhyDisks.some(item => {
            if(item.id == this.activeDisk) {
              this.phy_disk = item.disk+'?'+item.type+'@'+item.total +'#'+item.id;
              this.handleDiskChange(this.phy_disk);
            }
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },

    // 判断是否存在缓存池
    async isExistCachePool() {
      const res = await this.$api.osdManage.isExistCachePoolRequest();
      console.log('是否存在缓存池', res)
      if(res && res.data) {
        return res.data.have_tier
      }
    },

    //步骤一下一步的请求
    //获取未纳管盘的分区信息
    oneNextRequest() {
      return new Promise((resolve, reject) => {
        request('get', 'machine/disk/', {
          // params: {
            disk: this.nowDiskStr
          // }
        }).then(res => {
          resolve(res);
          // console.log('第一步请求', res)
          this.partitionData = res.data;
          if(res.data.length == 0) {
            this.hasPartition = false;
            this.isKeepOldPartition = false;
            this.oldPartiteNum = 0;
          }else {
            this.hasPartition = true;
            this.isKeepOldPartition = true;
            this.oldPartiteNum = res.data.length;
          }
        }).catch(err => {
          reject(err);
          console.log(err);
        })
      })
      
    },

    //步骤条下一步
    next() {
      if(this.current == 0) {
        if(this.activeDisk != -1) {
          this.handleDiskChange(this.phy_disk);
        }
        this.form.validateFields(async (err,value)=>{
          if(!err){
            this.phy_disk = this.form.getFieldValue('phy_disk');
            this.ssd_usage = this.form.getFieldValue('ssd_usage');
            if(this.diskType == 1) {
              this.diskUsage = 0;
            }else {
              this.diskUsage = this.ssd_usage;
            }
            try{
              let res = await this.oneNextRequest();
              if(res.data) { 
                this.current++;
              }
            }catch {
              this.$message.error(this.$t('Server-inner-error'))
            }
          }
        })
      }else if(this.current == 1) {
        this.form.validateFields((err,value)=>{
          if(!err){
            this.disk_partition = this.form.getFieldValue('disk_partition');
            this.current++;
          }
        })
      }
      
    },
    //步骤条上一步
    prev() {
      this.current--;
    },

    //磁盘选择
    handleChangeDisk(value) {
      console.log(value)
      this.handleDiskChange(value);
    },
    async handleDiskChange(value) {
      this.$emit('resetActiveDisk');
      this.phy_disk2 = value;
      const index1 = value.indexOf('?');
      const index2 = value.indexOf('@');
      const index3 = value.indexOf('#');
      this.nowDiskStr = value.substring(0, index1);
      this.diskType = value.substring(index1+1, index2);
      this.diskCapacity = value.substring(index2+1, index3);
      this.diskId = value.substring(index3+1);
      if(this.diskType == 0 || this.diskType == 2) {
        this.isShowSSDUsage = true;
        const isCachePool = await this.isExistCachePool();
        if(isCachePool) { // 如果存在缓存池，则可以创建缓存盘
          this.diskTypeData = this.diskTypeData_copy;
        }else {
          this.diskTypeData = this.diskTypeData.splice(0,1);
        }
      }else {
        this.isShowSSDUsage = false;
      }
    },

    //保留原有分区选择框
    onChangeCheckBox(e) {
      if(e.target.checked) {
        this.isKeepOldPartition = true;
        this.phy_disk = '';
      }else {
        this.isKeepOldPartition = false;
      }
    },

    //确认创建OSD
    confirmCreateOSD() {
      this.current++;
      let taskId = '';
      // console.log('1', this.disk_partition)
      // console.log('2', this.oldPartiteNum)
      // console.log('3', this.nowDiskStr)
      // console.log('4', this.diskId)
      // console.log('5', this.diskType)
      request('put', 'ops/osd/',{
        //new_count:以前有分区而且保留了分区值为-1
        partition_count: this.hasPartition && this.isKeepOldPartition?'-1':Number(this.disk_partition),
        // new_count: this.hasPartition && this.isKeepOldPartition?'-1':Number(this.disk_partition), //新分区的数量
        // old_count: this.oldPartiteNum, //旧分区的数量
        disk: this.nowDiskStr, //主机名：磁盘标识符
        disk_id: Number(this.diskId), //磁盘主键编号
        is_cache: Number(this.diskUsage), //0数据盘，1缓存盘
        wipe: Number(this.isKeepOldPartition) ? 0 : 1
      }).then(res => {
        // console.log('创建osd', res);
        this.model(res.data.id) //返回模板
        this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
        taskId = res.data.task_id;
        if(res.data.flag == 1) {
          this.createOSDStatus = 2;
        }else {
          this.createOSDStatus = 0;
          //轮询获取创建结果
          this.timer = setInterval(async() => {
            let res = await this.getOsdResult();
            res.data.some(item => {
              if(item.task_id == taskId) {
                if(item.state == 1) { //任务完成
                  if(item.flag == 0) { //如果osd成功
                    this.createOSDStatus = 1;
                  }else { //如果osd失败
                    this.createOSDStatus = 2;
                  }
                  clearInterval(this.timer);
                }else { //osd进行中
                  this.createOSDStatus = 0;
                }
              }
            })
          },2000)
        }
      }).catch(err => {
        console.log(err);
      })
    },

    //获取创建osd结果
    getOsdResult() {
      return new Promise((resolve, reject) => {
        request('put', 'logmanage/background_task/recent', {
          page_size: 10
        }).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
        })
      })
    },

    //重置
    resetFun() {
      this.ssd_usage = '';
      this.disk_partition = '';
      this.isKeepOldPartition = true;
      // this.isShowSSDUsage = false;
      this.createOSDStatus = 0;
    },

    //关闭弹窗
    cancelhandle() {
      this.$emit('closeDialog');
      this.form.resetFields();
      this.current = 0;
      this.phy_disk = '';
      this.ssd_usage = '';
      this.disk_partition = '';
      this.isKeepOldPartition = true;
      this.isShowSSDUsage = false;
      this.createOSDStatus = 0;
      clearInterval(this.timer);
    }
  }
}
</script>

<style scoped>
.steps-content {
  margin-top: 16px;
}
.tips {
  width: 100%;
  height: 100%;
  padding: 14px;
  margin: 5px 0;
  background-color: rgba(7, 133, 253, 0.1);
  border-radius: 4px;
  border: solid 1px var(--themeColor);
}
.tips img {
  margin-right: 5px;
  vertical-align: text-bottom;
}
.tips span > span {
  color: var(--themeColor);
  font-weight: 700;
}
.had-no-partition {
  text-align: center;
  color: #fff;
  padding: 10px;
  background-color: #f0f3f5;
}
.had-no-partition div:nth-child(1) {
  background-color: #c0c0c0;
}
.weightAndBlue {
  color:var(--themeColor);
  font-weight:700;
}
.weightAndRed {
  font-weight:700;
  color:var(--mainRedColor) !important;
}
.configIngImg,
.configIngImg2 {
  text-align: center;
  margin: 15px 0;
}
.configIngImg img {
  animation:iconRotate 2s linear infinite;
  -webkit-animation: iconRotate 2s linear infinite;
  -moz-animation: iconRotate 2s linear infinite;
  -o-animation: iconRotate 2s linear infinite;
}
@keyframes iconRotate{
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
}
.paragraph {
  text-align:left;
  text-indent:2em; 
}
</style>